from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc
from flask import jsonify
from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role
from applications.models import MarkLogs, AdminLog
from applications.schemas import UserSchema
from flask_cors import cross_origin
admin_dzt = Blueprint('adminDzt', __name__, url_prefix='/admin/dzt')
import json

# 用户管理
@admin_dzt.get('/')
@authorize("admin:user:main", log=True)
def main():
    return render_template('admin/dzt/index.html')

@admin_dzt.post('/add')
# @authorize("admin:user:add", log=True)
@cross_origin(supports_credentials=True)
def save():
    req_json = request.json
    imgurl = xss_escape(req_json.get('imgurl'))
    mark = req_json.get('mark')
    r = MarkLogs.query.filter_by(url=imgurl).update({"mark": str(mark)})
    if(not r):   # 存在即更新，不存在创建
        mark_item = MarkLogs(url=imgurl, mark=mark)
        db.session.add(mark_item)
    db.session.commit()
    return success_api(msg="更新成功～")



@admin_dzt.post('/getinfo')
@cross_origin(supports_credentials=True)
# @authorize("admin:user:add", log=True)
def getinfo():
    req_json = request.json
    imgurl = xss_escape(req_json.get('imgurl'))
    mark_list = MarkLogs.query.filter_by(url=imgurl).first()
    db.session.commit()
    if mark_list != None:
        data = {
            'msg': "标签获取成功",
            'data': mark_list.mark
        }
    else:
        data = {
            'msg': "此图片暂无标注",
            'data': []
        }
    return jsonify(data)